<?php

namespace Modules\Admin\app\Http\Middleware;

use App\Common\Enums\Code;
use App\Exceptions\ApiException;
use Closure;
use Exception;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;


class JwtCheck
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next)
    {
        // 从请求中获取 token，
        // $token = $request->header('Authorization');
        $token = $request->bearerToken();
        if (!$token) {
            throw new ApiException(Code::JWT_TOKEN_MISS, '用户信息不存在');
        }

        try {
            $auth = auth('admin_api')->parseToken()->checkOrFail();
        } catch (TokenInvalidException $e) {
            throw new ApiException(Code::JWT_TOKEN_INVALID, 'token信息不合法');
        } catch (TokenExpiredException $e) {
            throw new ApiException(Code::JWT_TOKEN_EXPIRED, 'token已过期');
        } catch (Exception $e) {
            throw new ApiException(Code::REQUEST_ERROR, '网络异常，请稍后重试');
        }

        return $next($request);
    }
}
